<template>
  <div
    id="EditProfileOverlay"
    class="fixed flex justify-center pt-14 md:pt-[105px] z-50 top-0 left-0 w-full h-full bg-black bg-opacity-50 overflow-auto"
  >
    <div
      class="relative bg-white w-full max-w-[700px] sm:h-[580px] h-[655px] mx-3 p-4 rounded-lg mb-10"
      :class="!uploadedImage ? 'h-[655px]' : 'h-[580px]'"
    >

      <div class="absolute flex items-center justify-between w-full p-5 left-0 top-0 border-b border-b-gray-300">
        <div class="text-[22px] font-medium">
          Edit profile
        </div>
        <button @click="$store.commit('general/change_isEditProfileOpen',false)">
          <Icon name="icon-guanbi" size="25"/>
        </button>
      </div>

      <div class="h-[calc(500px-200px)]" :class="!uploadedImage ? 'mt-16' : 'mt-[58px]'">
        <div v-if="!uploadedImage">
          <div
            id="ProfilePhotoSection"
            class="flex flex-col border-b sm:h-[118px] h-[145px] px-1.5 py-2 w-full"
          >
            <div class="font-semibold text-[15px] sm:mb-0 mb-1 text-gray-700 sm:w-[160px] sm:text-left text-center">
              Profile photo
            </div>

            <div class="flex items-center justify-center sm:-mt-6">
              <label for="image" class="relative cursor-pointer">
                <img
                  class="rounded-full"
                  width="95"
                  :src="userImage"
                >
                <div style="display: flex;align-items: center;justify-content: center"
                     class="h-[32px] absolute bottom-0 right-0 rounded-full bg-white shadow-xl border p-1 border-gray-300 inline-block w-[32px]">
                  <Icon name="icon-bianji1" size="17"/>
                </div>
              </label>
              <input
                class="hidden"
                type="file"
                id="image"
                @input="getUploadedImage"
                accept="image/png, image/jpeg, image/jpg"
              >
            </div>
          </div>

          <div
            id="UsernameSectionSection"
            class="flex flex-col border-b sm:h-[118px]  px-1.5 py-2 mt-1.5  w-full"
          >
            <div class="font-semibold text-[15px] sm:mb-0 mb-1 text-gray-700 sm:w-[160px] sm:text-left text-center">
              Username
            </div>

            <div class="flex items-center justify-center sm:-mt-6">
              <div class="sm:w-[60%] w-full max-w-md">
                <TextInput
                  placeholder="Username"
                  :input.sync="userName"
                  inputType="text"
                  max="30"
                />
                <div class="text-[11px] text-gray-500 mt-4">
                  Usernames can only contain letters, numbers, underscores, and periods.
                  Changing your username will also change your profile link.
                </div>
              </div>
            </div>
          </div>

          <div
            id="BioSection"
            class="flex flex-col sm:h-[120px]  px-1.5 py-2 mt-2 w-full"
          >
            <div class="font-semibold text-[15px] sm:mb-0 mb-1 text-gray-700 sm:w-[160px] sm:text-left text-center">
              Bio
            </div>

            <div class="flex items-center justify-center sm:-mt-6">
              <div class="sm:w-[60%] w-full max-w-md">
                                <textarea
                                  cols="30"
                                  rows="4"
                                  v-model="userBio"
                                  maxlength="80"
                                  class="
                                        resize-none
                                        w-full
                                        bg-[#F1F1F2]
                                        text-gray-800
                                        border
                                        border-gray-300
                                        rounded-md
                                        py-2.5
                                        px-3
                                        focus:outline-none
                                    "
                                ></textarea>
                <div v-if="userBio" class="text-[11px] text-gray-500">{{ userBio.length }}/80</div>
              </div>
            </div>
          </div>
        </div>

        <div v-else class="w-full h-[430px]">
          <Cropper
            class="h-[430px]"
            ref="cropper"
            :stencil-component="CircleStencil"
            :src="uploadedImage"
          />
        </div>
      </div>


      <div
        id="ButtonSection"
        class="absolute p-5 left-0 bottom-0 border-t border-t-gray-300 w-full"
      >
        <div
          id="UpdateInfoButtons"
          v-if="!uploadedImage"
          class="flex items-center justify-end"
        >
          <button
            @click="$store.commit('general/change_isEditProfileOpen',false)"
            class="flex items-center border rounded-sm px-3 py-[6px] hover:bg-gray-100"
          >
            <span class="px-2 font-medium text-[15px]">Cancel</span>
          </button>

          <button
            :disabled="!isUpdated"
            @click="updateUserInfo()"
            :class="!isUpdated ? 'bg-gray-200' : 'bg-[#F02C56]'"
            class="flex items-center bg-[#F02C56] text-white border rounded-md ml-3 px-3 py-[6px]"
          >
            <span class="mx-4 font-medium text-[15px]">Save</span>
          </button>
        </div>

        <div
          id="CropperButtons"
          v-else
          class="flex items-center justify-end"
        >
          <button
            @click="uploadedImage = null"
            class="flex items-center border rounded-sm px-3 py-[6px] hover:bg-gray-100"
          >
            <span class="px-2 font-medium text-[15px]">Cancel</span>
          </button>

          <button
            @click="cropAndUpdateImage()"
            class="flex items-center bg-[#F02C56] text-white border rounded-md ml-3 px-3 py-[6px]"
          >
            <span class="mx-4 font-medium text-[15px]">Apply</span>
          </button>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
import {Cropper, CircleStencil} from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css';

export default {
  components: {Cropper},
  data() {
    return {
      file: null,
      cropper: null,
      uploadedImage: null,
      userImage: null,
      userName: null,
      userBio: null,
      isUpdated: null,
      CircleStencil: CircleStencil
    }
  },
  computed: {
    $userStore() {
      return this.$store.state.user
    },
    $generalStore() {
      return this.$store.state.general
    },
    $profileStore() {
      return this.$store.state.profile
    },
  },
  watch: {
    userName: {
      handler(newVal) {
        if (!newVal || newVal === this.$userStore.name) {
          this.isUpdated = false
        } else {
          this.isUpdated = true
        }
      }
    },
    userBio: {
      handler(newVal) {
        if (!newVal || this.userBio.length < 1) {
          this.isUpdated = false
        } else {
          this.isUpdated = true
        }
      }
    },
  },
  methods: {
    getUploadedImage(e) {
      this.file = e.target.files[0]
      this.uploadedImage = URL.createObjectURL(this.file)
    },
    async cropAndUpdateImage() {
      const {coordinates} = this.$refs.cropper.getResult()
      let data = new FormData();
      data.append('image', this.file || '')
      data.append('height', coordinates.height || '')
      data.append('width', coordinates.width || '')
      data.append('left', coordinates.left || '')
      data.append('top', coordinates.top || '')

      try {
        await this.$store.dispatch('user/updateUserImage', data)
        await this.$store.dispatch('user/getUser')
        await this.$store.dispatch('profile/getProfile', this.$route.params.id)
        await this.$store.commit('general/updateSideMenuImage', {
          array: this.$generalStore.suggested, user: this.$userStore
        })
        await this.$store.commit('general/updateSideMenuImage', {
          array: this.$generalStore.following, user: this.$userStore
        })
        this.userImage = this.$userStore.image
        this.uploadedImage = null
      } catch (error) {
        console.log(error)
      }
    },
    async updateUserInfo() {
      try {
        await this.$store.dispatch('user/updateUser',{
          name:this.userName, bio:this.userBio
        })
        await this.$store.dispatch('user/getUser')
        await this.$store.dispatch('profile/getProfile',this.$route.params.id)
        await this.$store.commit('general/updateSideMenuUser', {
          array: this.$generalStore.suggested, user: this.$userStore
        })
        await this.$store.commit('general/updateSideMenuUser', {
          array: this.$generalStore.following, user: this.$userStore
        })
        this.userName = this.$userStore.name
        this.userBio = this.$userStore.bio
        setTimeout(() => {
          this.$store.commit('general/change_isEditProfileOpen',false)
        }, 100)
      } catch (error) {
        console.log(error)
      }
    }
  },
  mounted() {
    this.userName = this.$userStore.name
    this.userBio = this.$userStore.bio
    this.userImage = this.$userStore.image
  }
}
</script>
